//
//  ViewDetailController.swift
//  amicoolView
//
//  Created by 王睿 on 2017/6/14.
//  Copyright © 2017年 王睿. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit

class ViewDetailController: UIViewController {
    var videoModel:VideoReturnJson? = nil
    @IBOutlet weak var playerView: UILabel!
    var avPlayer:AVPlayer! //播放器
    var playerLayer:AVPlayerLayer!//播放器图层，需要将视频层添加到图层上才能显示
    var controlView:UIView!   //控制条视图
    var playBt:UIButton! //播放按钮
    var slider:UISlider! //滑动条
    var slideing:Bool = true //滑动条状态
    var timeLab:UILabel! //时间标签
    var hideState:Bool = false  //状态
    
    var obser:Any! //监听器
    @IBOutlet weak var videoTitle: UILabel!
    @IBOutlet weak var author: UILabel!
    @IBOutlet weak var course: UILabel!
    @IBOutlet weak var timeUpload: UILabel!
    @IBOutlet weak var desc: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 226/25)
        //左上角导航条按钮
        let bt = UIButton(frame:  CGRect(x: 0, y: 0, width: 28, height: 28))
        bt.setImage(UIImage(named:"back.png"), for: .normal)
        bt.addTarget(self, action: #selector(ViewDetailController.back), for: .touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: bt)
        self.navigationItem.leftBarButtonItem?.tintColor = UIColor.white
        
        //播放页面配置
        avPlayerConfiguration()
        //控制条视图，带有阴影效果，添加至图层
        //初始化详情信息
        if self.videoModel != nil {
            self.videoTitle.text = self.videoModel?.name
            self.author.text = self.videoModel?.author
            self.desc.text = self.videoModel?.desc
            self.course.text = self.videoModel?.kcmc
            self.timeUpload.text = self.videoModel?.update_time
        }
        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func back(){
        avPlayer.removeTimeObserver(obser)
        avPlayer.currentItem?.asset.cancelLoading()
        avPlayer.currentItem?.cancelPendingSeeks()
        avPlayer.replaceCurrentItem(with: nil)
        avPlayer = nil
        playerLayer.removeFromSuperlayer()
        playerLayer = nil
        _ = navigationController?.popViewController(animated: true)
        
    }
    func avPlayerConfiguration(){
        playerView.layer.masksToBounds = true
        playerView.backgroundColor = UIColor.black
        //添加单击手势
        playerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showControlV)))
        let width = self.view.bounds.width
        let height = playerView.bounds.height
        view.addSubview(playerView)
        
        //创建播放器，保持视频比例填充到图层
        avPlayer = AVPlayer(url: URL(string: videoModel!.videopath!)!)
        playerLayer = AVPlayerLayer(player: avPlayer)
        playerLayer.frame = CGRect(origin: CGPoint.zero, size: playerView.frame.size)
        playerLayer.videoGravity = AVVideoScalingModeResizeAspect
        playerView.layer.addSublayer(playerLayer)
        
        //控制条视图，带有阴影效果，添加到图层
        controlView = UIView(frame: CGRect(x: 0, y: height-35, width: width, height: 35))
        controlView.backgroundColor = UIColor.clear
        let blurEffectView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 35))
        blurEffectView.layer.opacity = 0.5
        controlView.addSubview(blurEffectView)
        playerView.addSubview(controlView)
        
        //播放按钮，添加到控制条视图
        playBt = UIButton(frame: CGRect(x: 10, y: 5, width: 25, height: 25))
        playBt.setImage(UIImage(named:"play.png"), for: .normal)
        playBt.tintColor = UIColor.white
        playBt.addTarget(self, action: #selector(play), for: .touchUpInside)
        controlView.addSubview(playBt)
        
        //满屏播放按钮，添加到控制条视图
        let fullBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        fullBtn.center = CGPoint(x: width-35+25/2, y: playBt.center.y)
        fullBtn.setImage(UIImage(named:"full.png"), for: .normal)
        fullBtn.tintColor = UIColor.white
        fullBtn.addTarget(self, action: #selector(fullScreen), for: .touchUpInside)
        controlView.addSubview(fullBtn)
        
        //滑动条，添加到控制条视图
        slider = UISlider(frame: CGRect(x: 0, y: 0, width: width-140, height: 5))
        slider.center = CGPoint(x: 40+width/2-70, y: playBt.center.y)
        slider.maximumValue = 1
        slider.minimumValue = 0
        slider.value = 0
        let thumbImg = UIImage(named: "slider.png")?.scaleImageToSize(CGSize(width: 10, height: 10))
        slider.setThumbImage(thumbImg, for: .normal)
        slider.addTarget(self, action: #selector(slidertouchDown), for: .touchDown)
        slider.addTarget(self, action: #selector(slidertouchOut), for: .touchUpInside)
        controlView.addSubview(slider)
        
        //时间标签，添加至控制条视图
        timeLab = UILabel(frame: CGRect(x: 0, y: 0, width: 65, height: 20))
        timeLab.center = CGPoint(x: width-62, y: playBt.center.y)
        timeLab.text = "00:00/00:00"
        timeLab.font = UIFont.systemFont(ofSize: 10)
        timeLab.backgroundColor = UIColor.clear
        timeLab.textColor = UIColor.white
        controlView.addSubview(timeLab)
        //监听，播放过程
        addObser()
        //延迟3秒后执行隐藏控制条视图
        self.perform(#selector(self.hideControlV), with: self, afterDelay: 3)
        
    }
    func addObser(){
        obser = avPlayer.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1), queue: .main){ [weak self](time) in
            var totalSec:String!
            var currentSec:String!
            let currentTime = CMTimeGetSeconds(time)
            let totalTime = CMTimeGetSeconds((self?.avPlayer.currentItem?.duration)!)//视频总时长
            
            if (self?.slideing)!{
                self?.slider.setValue(Float(currentTime/totalTime), animated: true)
            }
            if currentTime.isNaN || totalTime.isNaN{
                totalSec = "00:00"
                currentSec = "00:00"
            }
            else{
                totalSec = String(format: "%02d:%02d", Int(totalTime/60), Int(totalTime.truncatingRemainder(dividingBy: 60)))
                currentSec = String(format: "%02d:%02d", Int(currentTime/60), Int(currentTime.truncatingRemainder(dividingBy: 60)))
            }
            self?.timeLab.text = "\(currentSec!)/\(totalSec!)"
        }
        
    }
    
    //显示播放控制条
    func showControlV(){
        if controlView.frame.origin.y == playerView.bounds.height{
            UIView.animate(withDuration: 0.2, animations: {
                self.controlView.frame.origin.y = self.playerView.bounds.height - self.controlView.bounds.height
            }, completion: { (_) in
                self.perform(#selector(self.hideControlV), with: self, afterDelay: 3)
            })
        }
        else{
            
        }
    }
    //播放视频
    func play(){
        if avPlayer.rate == 0{
            avPlayer.play()
            playBt.setImage(UIImage(named:"pause.png"), for: .normal)
        }
        else if avPlayer.rate == 1 {
            avPlayer.pause()
            playBt.setImage(UIImage(named:"play.png"), for: .normal)
        }
    }
    func fullScreen(){
        let w = UIScreen.main.bounds.width
        let h = UIScreen.main.bounds.height
        let pw = playerView.bounds.width
        let ph = playerView.bounds.height
        if !hideState{
            view.bringSubview(toFront: playerView)
            UIView.animate(withDuration: 0.3, animations: {
                self.playerView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/180)*CGFloat(90)).concatenating(CGAffineTransform(scaleX: w/ph, y: h/pw)).concatenating(CGAffineTransform(translationX: 0, y: 233.5-64))
            })
            hideState = !hideState
            self.setNeedsStatusBarAppearanceUpdate()
        }
        else{
            UIView.animate(withDuration: 0.3, animations: {
                self.playerView.transform = .identity
            })
            hideState = !hideState
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    func  hideControlV(){
        let animation = CABasicAnimation(keyPath: "positon.y")
        animation.duration = 0.2
        self.controlView.layer.frame.origin.y = self.playerView.bounds.height
        self.controlView.layer.add(animation, forKey: nil)
        
        
    }
    //滑动条
    func slidertouchDown(){
        slideing = !slideing
    }
    func
        slidertouchOut(){
        avPlayer.seek(to:CMTime(seconds: Double(self.slider.value*Float(CMTimeGetSeconds((self.avPlayer.currentItem?.duration)!))), preferredTimescale: 1)){[weak self](_) in
            self!.slideing = !(self!.slideing)
            
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
